package com.bugstack.domain.activity.service.quota.rule.impl;

import com.bugstack.domain.activity.service.armory.IActivityDispatch;
import com.bugstack.domain.activity.model.entity.ActivityCountEntity;
import com.bugstack.domain.activity.model.entity.ActivityEntity;
import com.bugstack.domain.activity.model.entity.ActivitySkuEntity;
import com.bugstack.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import com.bugstack.domain.activity.reopsitory.IActivityRepository;
import com.bugstack.domain.activity.service.quota.rule.AbstractActivityChain;
import com.bugstack.types.enums.ResponseCode;
import com.bugstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: czb
 * @Description: sku校验节点
 * @DateTime: 2025/3/21 16:04
 **/
@Component("activity_sku_stock_action")
@Slf4j
public class ActivitySkuStockActionChain extends AbstractActivityChain {

    @Resource
    private IActivityDispatch activityDispatch;
    @Resource
    private IActivityRepository repository;

    @Override
    public void action(ActivitySkuEntity activitySkuEntity, ActivityEntity activityEntity, ActivityCountEntity activityCountEntity) {
        log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】开始。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
        Long sku = activitySkuEntity.getSku();
        Long activityId = activitySkuEntity.getActivityId();
        //1.扣减库存
        boolean state = activityDispatch.subtractionActivitySkuStock(sku, activityEntity.getEndDateTime());

        if (state) {
            log.info("活动责任链-商品库存处理【有效期、状态、库存(sku)】成功。sku:{} activityId:{}", activitySkuEntity.getSku(), activityEntity.getActivityId());
            //2.向延时队列发送消息
            repository.activitySkuStockConsumeSendQueue(ActivitySkuStockKeyVO.builder().sku(sku).activityId(activityId).build());
            return;
        }

        throw new AppException(ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getCode(), ResponseCode.ACTIVITY_SKU_STOCK_ERROR.getInfo());
    }
}
